<template>
    <div class="page-home">
        <PanelHead :title="panelTitle" :description="panelDescription"/>
        <div class="btns">
            <el-button icon="Plus" type="primary" @click="open(null)" >新增陪护师</el-button>
            <el-popconfirm
                confirm-button-text="是"
                cancel-button-text="否"
                icon="InfoFilled"
                icon-color="#626AEF"
                title="是否确认删除"
                @confirm="confirmEvent"
        >
            <template #reference>
                <el-button type="danger" icon="Delete" >删除</el-button>
            </template>
        </el-popconfirm>
        </div>
        <el-dialog
                v-model="dialogFormVisible"
                :title="form.id > 0 ? '编辑陪护信息':'新增陪护师'"
                width="500"
                :before-close="beforeClose"
        >
            <el-form
                    ref="formRef"
                    label-width="100px"
                    label-position="left"
                    :model="form"
                    :rules="rules"
            >
                <el-form-item v-show="false" prop="id">
                    <el-input v-model="form.id" />
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" placeholder="请填写" />
                </el-form-item>

                <el-form-item label="头像" prop="avatar">
                    <!-- 如果没头像数据 则 出现按钮，如果有头像按钮 则显示图片-->
                    <el-button type="primary" v-if="!form.avatar" @click="dialogAvatarVisible = true" >点击上传</el-button>
                    <el-image v-else :src="form.avatar"
                        style="width: 100px; height: 100px"
                    >

                    </el-image>
                </el-form-item>

                <el-form-item label="性别" >
                    <!-- 下拉 -->
                    <el-select
                            v-model="form.sex"
                            placeholder="请选择"
                            size="large"
                            style="width: 240px"
                    >
                        <el-option
                                v-for="item in sexOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="form.age" :min="18" :max="50" @change="handleChange" />
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="form.mobile" placeholder="请填写" />
                </el-form-item>


                <el-form-item label="状态" prop="active">
                    <el-radio-group v-model="form.active">
                        <el-radio :value="1" >有效</el-radio>
                        <el-radio :value="0" >无效</el-radio>
                    </el-radio-group>
                </el-form-item>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirm(formRef)" >确认</el-button>
                </div>
            </template>

        </el-dialog>

        <!--头像对话框-->
        <el-dialog
                v-model="dialogAvatarVisible"
                title="上传头像"
                width="680"
                :before-close="beforeCloseAvatar"
        >
            <div class="image-list">
                <div v-for="(item, index ) in avatarList " :key="item.index" class="img-box" @click="selectIndex = index">
                    <div v-if="selectIndex === index" class="select">
                        <el-icon color="#fff"><Check /></el-icon>
                    </div>
                    <el-image style="width: 148px;height: 148px"
                        :src="item"
                    >

                    </el-image>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="confirmImage()" >确认</el-button>
                    <el-button type="primary" @click="dialogAvatarVisible = false" >取消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-table :data="tableData.list" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />

            <el-table-column prop="id" label="id"  width="90" />
            <el-table-column prop="name" label="姓名"  />
            <el-table-column prop="age" label="年龄"  />
            <el-table-column prop="avatar"  label="头像"  >
                <template #default="scope">
                    <el-image style="width: 50px; height: 50px" :src="scope.row.avatar"></el-image>
                </template>
            </el-table-column >
            <el-table-column prop="sex"  label="性别"  >
                <template #default="scope">
                    <el-tag :type="scope.row.sex==1 ? 'success':'danger'">{{ scope.row.sex==1 ? '男':'女' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="mobile" label="手机号"  />
            <el-table-column prop="active" label="状态"  >
                <template #default="scope">
                    <el-tag :type="scope.row.active==1 ? 'success':'danger'">{{ scope.row.active==1 ? '正常':'失效' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间"  >
                <template #default="scope">
                    <div class="flex-box">
                        <el-icon><Clock /></el-icon>
                        <span style="margin-left: 10px"> {{ scope.row.createTime }} </span>
                    </div>

                </template>
            </el-table-column>

            <el-table-column label="操作" width="180" >
                <template #default="scope">
                    <el-button type="primary" @click="open(scope.row)">编辑</el-button>
                </template>
            </el-table-column>


        </el-table>
        <div class="pagination-info">
            <el-pagination
                    v-model:current-page="paginationData.pageNum"
                    :page-size="paginationData.pageSize"
                    size="small"
                    :background="false"
                    layout="total, prev, pager, next"
                    :total="tableData.total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
            >

            </el-pagination>
        </div>

    </div>
</template>
<script setup>
 import {ref, reactive, computed, toRaw, nextTick, onMounted} from 'vue'
 import { photoList, addStuff, stuffList, updateStuff, batchDeleteStuff } from  '../../../api/modules/stuffApi'

 // 服务器的 IP 和端口
 const serverIp = 'localhost';
 const serverPort = '8090';

 onMounted(()=>{

     // 发送请求，获得表格数据
     getTableData();


     photoList().then(({data}) => {
         console.log('头像数据',data);

         avatarList.value = data.data;

         function prependServerUrl(relativePath) {
             return `http://${serverIp}:${serverPort}${relativePath}`;
         }

         // 处理数据并更新 avatarList
         if (Array.isArray(data.data)) {
             // 使用 map 方法来遍历每个相对路径并添加前缀
             const fullUrls = data.data.map(prependServerUrl);
             // 更新 avatarList 为包含完整 URL 的数组
             avatarList.value = fullUrls;
         } else {
             console.error('预期 data.data 是一个数组，但接收到的是：', data.data);
         }

     });
 });



 // 下拉选项
 const options = [
     { value: 0, label: '失效' },
     { value: 1, label: '正常' },
 ];

 // 下拉选项
 const sexOptions = [
     { value: 1, label: '男' },
     { value: 2, label: '女' },
 ];

 const dialogTitle = ref('窗口标题');
 // 弹窗的显示隐藏
 const dialogFormVisible = ref(false);
 // 头像弹窗的显示隐藏
 const dialogAvatarVisible = ref(false);

 const avatarList = ref([]);
 const selectIndex = ref(0);

 // 关闭弹窗的回调
 const beforeClose = () => {
     console.log("关闭弹窗--call");
     dialogFormVisible.value = false;
     // 重置表单
     formRef.value.resetFields();

 };

 // 头像确认
 const confirmImage = () => {
     form.avatar = avatarList.value[selectIndex.value];
     dialogAvatarVisible.value = false;
 };

 // 编辑表单
 const formRef = ref();

 // 表单数据定义
 const form = reactive(
     {
         id: '',
         name: '',
         active: 1,
         age: 18,
         avatar: '',
         sex: '',
         mobile:''
     });

 // 分页定义
 const paginationData = reactive({
     pageNum: 1,
     pageSize: 10
 });

 // 列表数据
 const tableData = reactive({
     list:  [
     ],
     total: 1
 });

 // 请求列表数据
 const getTableData = () => {
     stuffList(paginationData).then(({ data }) => {
         const { list, total } = data.data;
         tableData.list = list;
         tableData.total = total;
     } )
 };
    // 打开弹窗
 const open = ( rowData = {} ) => {
     dialogFormVisible.value = true;

     // 弹窗打开form生成是异步的 如果新增和编辑是复用一个
     nextTick(() => {
             // 编辑页面赋值
             if(rowData){
                 // 赋值给form
                Object.assign(form,rowData);
             }
         }
     )
 };

 const openAvatarDialog = ( rowData = {} ) => {
     dialogAvatarVisible.value = true;
 };

 const handleChange = (val) => {
    // console.log("change ",val)
 };

 // 关闭弹窗的回调
 const beforeCloseAvatar = () => {
     dialogAvatarVisible.value = false;
 };

 // 用户名校验
 const validateName = (rule,value,callback) => {
     if(value === ''){
         callback(new Error('名称不能为空'));
     }
     callback();
 };

 // 手机号校验
 const validateMobile = (rule,value,callback) => {
     if(value === ''){
         callback(new Error('手机号不能为空'));
     }
     callback();
 };

 // 状态校验
 const validateActive = (rule,value,callback) => {
     if(value === ''){
         callback(new Error('请选择状态'));
     }
     callback();
 };

 // 表单校验 blur失去焦点时触发
 const rules = reactive({
     // name: [{ validator : validateName, trigger: 'blur'}],
     // mobile: [{ validator : validateMobile, trigger: 'blur'}]
     name: [{ required : true, trigger: 'blur', message: '请填写'}],
     avatar: [{ required : true, trigger: 'blur', message: '请选择头像'}],
     mobile: [{ required : true, trigger: 'blur', message: '请填写手机号'}]
 });

 // 页面数据变更
 const handleSizeChange = (val) => {
     //console.log('数据变更');
     paginationData.pageNum = val;
     getTableData();
 };

 // 当前页码改变
 const handleCurrentChange = (val) => {
     //console.log('页面变更');
     paginationData.pageNum = val;
     getTableData();
 };

 // 表单提交
 const confirm = async (formEl) => {
     if(!formEl) return;
     if( form.id > 0){
         // 发送修改请求
         updateStuff({
             id: form.id,
             name: form.name,
             age: form.age,
             avatar: form.avatar,
             mobile: form.mobile,
             active: form.active,
             sex: form.sex
         }).then( ({data}) => {
             if (data.code === '0'){
                 ElMessage.success(data.data);
             }else{
                 // 失败提示
             }
             // 关闭弹窗
             beforeClose();
             // 请求列表数据
             getTableData();
         });
     }else {
         // 发送新增请求
         addStuff({
             name: form.name,
             avatar: form.avatar,
             age: form.age,
             mobile: form.mobile,
             active: form.active,
             sex: form.sex
         }).then( ({data}) => {
             if (data.code === '0'){
                 ElMessage.success(data.data);
             }else{
                 // 失败提示
             }
             // 关闭弹窗
             beforeClose();
             // 请求列表数据
             getTableData();
         });
     }




 };
 // 选中的id
 const selectTableData = ref([]);
 const handleSelectionChange = (val) => {
     console.log("change!",val);
     // selectTableData.value = val;
     selectTableData.value = val.map(item => item.id);
 };

 // 确认删除点击
 const confirmEvent = () => {
     if(!selectTableData.value.length){
         return ElMessage.warning("请选择至少一项数据!");
     }
     //console.log(" 需要删除的data ",selectTableData.value);
     // 发送批量删除请求
     batchDeleteStuff( selectTableData.value).then( ({data}) => {
         if (data.code === '0'){
             ElMessage.success(data.data);
         }else{
             // 失败提示
         }
         // 请求列表数据
         getTableData();
     });
 };

 const panelTitle = ref('陪护管理');
 const panelDescription = ref('陪护师可以进行创建和修改，设置对应生效状态控制');

</script>
<style lang="less" scoped>
    .btns {
        padding: 10px 0 10px 10px;
        background-color: #fff;
    }
    .image-list {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .img-box {
            position: relative;
            .select {
                position: absolute;
                left: 0px;
                top: 0px;
                width: 24px;
                height: 24px;
                background-color: #67c23a;
                z-index: 999;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        }
        .el-image {
            margin-right: 10px;
            margin-bottom: 10px;
        }
    }
</style>
